package com.polaris.live.popup

import android.content.Context
import android.view.View
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventMessage
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.common.network.manualRequest
import com.polaris.live.common.util.DateUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.loading.LoadingUtils
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.DialogCompleteGenderBinding
import com.polaris.live.net.userService
import com.polaris.live.resp.go_resp.QuickModifyBean
import com.polaris.live.translation.R.string
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

/**
 * CompleteSexDialog
 *
 * @author Created by lucas on 2024/5/16 07:19
 */
class CompleteGenderDialog(
    context: Context,
    private val mOnIsOK: () -> Unit,
) : BottomPopupView(context) {

    private lateinit var mBinding: DialogCompleteGenderBinding

    private var mGender: Int? = null

    private var mUpdateJob: Job? = null

    private var mCompleteJob: Job? = null

    override fun getImplLayoutId(): Int {
        return R.layout.dialog_complete_gender
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogCompleteGenderBinding.bind(popupImplView)

        initNetWork()
        initData()
    }

    private fun initNetWork() {
        //判断当前广告来源
        val trafficSourceType = UserManager.getUser().flag?.trafficSourceType
        if (trafficSourceType == UserConst.FlagFrom.FB_COME) {
            mBinding.root.post {
                mBinding.manSelect.performClick()
            }
        } else {
            mCompleteJob = CoroutineScopeManager.mainScope.launch {
                try {
                    manualRequest({ userService.getUserTrafficSource() },
                        {
                            UserManager.getUser().flag?.trafficSourceType = it.trafficSourceType

                            if (it.selectedMale) {
                                mBinding.root.post {
                                    mBinding.manSelect.performClick()
                                }
                            }
                        }, {})
                } finally {
                    if (mCompleteJob == coroutineContext[Job]) {
                        mCompleteJob = null
                    }
                }
            }
        }
    }

    private fun initData() {
        mBinding.apply {

            val birthday = UserManager.getUser().birthday

            if (birthday == null) {
                val calendar = Calendar.getInstance()
                calendar.add(Calendar.YEAR, -19)

                val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                val formattedDate = dateFormat.format(calendar.time)

                birthdaySelect.text = formattedDate.convertArabicDigitsToNormal()
            } else {
                val dateString = DateUtils.convertTimestampToString(birthday)
                birthdaySelect.text = dateString?.convertArabicDigitsToNormal()
            }

            manSelect.setOnSingleClickListener {
                if (mGender != AppConst.UserSex.MAN) {
                    mGender = AppConst.UserSex.MAN
                    manSelect.isSelected = true
                    womanSelect.isSelected = false
                    manSelectImg.isSelected = true
                    womanSelectImg.isSelected = false
                    manSelectMark.visibility = View.VISIBLE
                    womanSelectMark.visibility = View.GONE
                    manSelect.alpha = 1f
                    womanSelect.alpha = 0.4f
                }
            }
            womanSelect.setOnSingleClickListener {
                if (mGender != AppConst.UserSex.WOMAN) {
                    mGender = AppConst.UserSex.WOMAN
                    manSelect.isSelected = false
                    womanSelect.isSelected = true
                    manSelectImg.isSelected = false
                    womanSelectImg.isSelected = true
                    manSelectMark.visibility = View.GONE
                    womanSelectMark.visibility = View.VISIBLE
                    manSelect.alpha = 0.4f
                    womanSelect.alpha = 1f
                }
            }

            conTime.setOnSingleClickListener {
                XPopup.Builder(context)
                    .isDestroyOnDismiss(true)
                    .asCustom(
                        DataSelectPopup(
                            context,
                            mOnSelectCallBack = { year, month, day ->
                                birthdaySelect.text = "${year}-${month}-${day}".convertArabicDigitsToNormal()
                                birthdaySelect.setTextColor(ColorUtils.getColor(R.color.f202028))
                                birthdayImg.visibility = VISIBLE
                            }, birthday
                        )
                    )
                    .show()
            }

            tvSubmit.setOnSingleClickListener {
                val gender = mGender
                if (gender != null) {

                    val birthday = birthdaySelect.text.toString()
                    val infoModifyBean = QuickModifyBean(
                        UserManager.getUser().nickname ?: "",
                        birthday,
                        sex = gender,
                        1
                    )

                    mUpdateJob = CoroutineScopeManager.mainScope.launch {
                        LoadingUtils.showLoadingDialog(context, context.getString(string.loading), useView = false)

                        try {
                            manualRequest(
                                { userService.quickModify(infoModifyBean) },
                                { updateSuccess() },
                                { ToastGravity.showGravity(it.errorMsg) }
                            )
                        } finally {
                            LoadingUtils.dismissLoadingDialog()

                            if (mUpdateJob == coroutineContext[Job]) {
                                mUpdateJob = null
                            }
                        }
                    }
                } else {
                    ToastGravity.showGravity(StringUtils.getString(string.please_complete_the_information))
                }
            }
        }
    }

    private fun updateSuccess() {
        if (mGender != null) {
            UserManager.getUser().sex = mGender as Int
        }
        mOnIsOK.invoke()
        EventBus.getDefault().post(EventMessage(BizEventConst.INFO_UPDATA))
        dismiss()
    }

    override fun onDismiss() {
        super.onDismiss()

        mUpdateJob?.cancel()
        mUpdateJob = null

        mCompleteJob?.cancel()
        mCompleteJob = null
    }
}